﻿/* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 
Copyright (C) 2010 by Tomasz Pluskiewicz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */

using System;
using System.Web.Security;

namespace Yama.MVC.Security
{
    /// <summary>
    /// Based on http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html
    /// </summary>
    public abstract class AbstractIoCRoleProvider : RoleProvider
    {
        protected string ProviderId;

        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
            base.Initialize(name, config);
            ProviderId = config["providerId"];
            if (string.IsNullOrWhiteSpace(ProviderId))
                throw new Exception("Please configure the providerId from the role provider " + name);
        }

        private T WithProvider<T>(Func<RoleProvider, T> f)
        {
            var provider = GetProvider();
            try
            {
                return f(provider);
            }
            finally
            {
                ReleaseProvider(provider);
            }
        }

        private void WithProvider(Action<RoleProvider> f)
        {
            var provider = GetProvider();
            try
            {
                f(provider);
            }
            finally
            {
               ReleaseProvider(provider);
            }
        }

        protected abstract RoleProvider GetProvider();
        
        protected abstract void ReleaseProvider(RoleProvider provider);

        public override sealed bool IsUserInRole(string username, string roleName)
        {
            return WithProvider(p => p.IsUserInRole(username, roleName));
        }

        public override sealed string[] GetRolesForUser(string username)
        {
            return WithProvider(p => p.GetRolesForUser(username));
        }

        public override sealed void CreateRole(string roleName)
        {
            WithProvider(p => p.CreateRole(roleName));
        }

        public override sealed bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            return WithProvider(p => p.DeleteRole(roleName, throwOnPopulatedRole));
        }

        public override sealed bool RoleExists(string roleName)
        {
            return WithProvider(p => p.RoleExists(roleName));
        }

        public override sealed void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            WithProvider(p => p.AddUsersToRoles(usernames, roleNames));
        }

        public override sealed void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            WithProvider(p => p.RemoveUsersFromRoles(usernames, roleNames));
        }

        public override sealed string[] GetUsersInRole(string roleName)
        {
            return WithProvider(p => p.GetUsersInRole(roleName));
        }

        public override sealed string[] GetAllRoles()
        {
            return WithProvider(p => p.GetAllRoles());
        }

        public override sealed string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            return WithProvider(p => p.FindUsersInRole(roleName, usernameToMatch));
        }

        public override sealed string ApplicationName { get; set; }
    }
}